package com.mouse.magent.common.handler;

import com.mouse.magent.common.protocol.Command;
import com.mouse.magent.common.protocol.Message;
import com.mouse.magent.common.util.NettyUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class CommonHandler extends ChannelInboundHandlerAdapter {

    protected ChannelHandlerContext ctx;

    public ChannelHandlerContext getCtx() {
        return ctx;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                log.info("ip:{} Read idle loss connection.", NettyUtil.getRemoteIp(ctx));
                ctx.close();
            } else if (e.state() == IdleState.WRITER_IDLE) {
                Message natxMessage = new Message();
                natxMessage.setType(Command.KEEP_ALIVE);
                ctx.writeAndFlush(natxMessage);
            }
        }
    }
}
